//save,get
const express=require('express');
// const async=require('async')
const router=express.Router();
const passport=require("passport");
const mongoose=require("mongoose");
const everyPageCount=require("../../config/keys").everyPageCount;

const Post=require('../../models/Post');


//$route  Post api/posts/savePost
//@desc   return state
//@access private
router.post("/savePost",passport.authenticate("jwt",{session:false}),(req,res)=>{
    let post=new Post({
        author:req.user.id,
        title:req.body.title,
        content:req.body.content,
    })
    post.save((err)=>{
        if(err){
            res.json({"ok":1});
        }
        else{
            res.json({"ok":0});
        }
    })
})

//$route  Post api/posts/getHostPosts
//@desc   return posts
//@access public
router.post('/getHostPosts',(req,res)=>{
    let page=req.body.page-1;
    Post
    .aggregate([{$lookup:{
        from:'users',
        localField:'author',
        foreignField:'_id',
        as:'author',
    }},
    {
        $lookup:{
        from:'comments',
        localField:'_id',
        foreignField:'post',
        as:'comments',
    }},
    {
        $lookup:{
        from:'greats',
        localField:'_id',
        foreignField:'post',
        as:'greats',
    }},
    {
        $lookup:{
        from:'reads',
        localField:'_id',
        foreignField:'post',
        as:'reads',
    }},
    {
        $unwind:'$author',
    },
    {
        $sort:{'postDate':-1},
    },
    {
        $skip:everyPageCount*page,
    },
    {
        $limit:everyPageCount,
    },
    {
        $project:{
            title:1,
            content:'$content',
            postDate:'$postDate',
            author:{'_id':'$author._id','name':'$author.name','avatar':'$author.avatar'},
            commentsCount:'$comments._id',
            greatsCount:'$greats._id',
            readsCount:'$reads._id',
        }
    }
    ])
    .exec((err,posts)=>{
        if(err){
            console.log(err)
            res.json({'ok':1,'data':[]});
        }
        else{
            // getPostUser(posts,(users)=>{
                // console.log(posts);
                for(let i=0;i<posts.length;i++){
                    posts[i].commentsCount=posts[i].commentsCount.length;
                    posts[i].greatsCount=posts[i].greatsCount.length;
                    posts[i].readsCount=posts[i].readsCount.length;
                }
                res.json({'ok':0,'data':posts});
            // })
        }
    })
})

//$route  Post api/posts/getUserPosts
//@desc   return posts 有个用户的所有博客
//@access public
router.post('/getUserPosts',(req,res)=>{
    let author=req.body.user;
    Post
    .aggregate([
    {
        $match:{'author':mongoose.Types.ObjectId(author)}
    },
    {
        $lookup:{
        from:'comments',
        localField:'_id',
        foreignField:'post',
        as:'comments',
    }},
    {
        $lookup:{
        from:'greats',
        localField:'_id',
        foreignField:'post',
        as:'greats',
    }},
    {
        $lookup:{
        from:'reads',
        localField:'_id',
        foreignField:'post',
        as:'reads',
    }},
    {
        $sort:{'postDate':-1},
    },
    {
        $project:{
            title:1,
            content:'$content',
            postDate:'$postDate',
            commentsCount:'$comments._id',
            greatsCount:'$greats._id',
            readsCount:'$reads._id',
        }
    }
    ])
    .exec((err,posts)=>{
        if(err){
            console.log(err)
            res.json({'ok':1,'data':[]});
        }
        else{
            for(let i=0;i<posts.length;i++){
                posts[i].commentsCount=posts[i].commentsCount.length;
                posts[i].greatsCount=posts[i].greatsCount.length;
                posts[i].readsCount=posts[i].readsCount.length;
            }
            res.json({'ok':0,'data':posts});
        }
    })
})
// function getPostUser(posts,callback){
//     let users=[];
//     users=async.map(posts,(value,callback2)=>{
//         User.findById(value.author,{'_id':1,'name':1,'avatar':1})
//         .then((user)=>{
//             callback2(null,user);
//         })
//         .catch(err=>{
//             console.log(err);
//         })
//     },(err,users)=>{
//         callback(users);
//     })
// }
//获取post数量
router.post('/getPostsCount',(req,res)=>{
    Post.countDocuments()
    .then(count=>{
        if(count%everyPageCount!=0){
            count=parseInt(count/everyPageCount)+1;
        }
        else{
            count=parseInt(count/everyPageCount);
        }
        res.send({"data":count});
    })
})

module.exports=router;